package com.zxj.camerapreview;

import android.app.Activity;
import android.content.Context;
import android.graphics.ImageFormat;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.os.Build;
import android.os.Bundle;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;

import androidx.appcompat.app.AppCompatActivity;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

import cn.iotnova.rtc.ISignalcallback;
import cn.iotnova.rtc.Rtcclient;
import cn.iotnova.rtc.TestView;
import cn.iotnova.rtc.WebsocketSignal;



public class NativeRtcActivity extends AppCompatActivity implements SurfaceHolder.Callback, Camera.PreviewCallback {
	TestView view = null;
	int i = 1;

	Rtcclient rtcclient = new Rtcclient();

	WebsocketSignal mWebSocketClient;

	private SurfaceView mSurfaceView;
	private SurfaceHolder mHolder;
	private Camera mCamera;
	private Camera.Parameters mParameters;
	private int camera_status = 0;

	private int permissionRequestCode;

	int width = 640;
	int height = 480;

	volatile boolean isDestroy = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		//DisplayMetrics dm = new DisplayMetrics();
		//getWindowManager().getDefaultDisplay().getMetrics(dm);
		//int width=dm.widthPixels;
		//int height=dm.heightPixels;
		//Log.i("JNI_LOG", "screenWidth = "+width+"screenHeight"+height);

		setContentView(R.layout.rtcmain);



		mSurfaceView = (SurfaceView)findViewById(R.id.rtcSurfaceView);
		mHolder = mSurfaceView.getHolder();
		mHolder.addCallback(this);
		mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

		/*
		view = findViewById(R.id.testView);

		view.setZOrderOnTop(true);
		view.setZOrderMediaOverlay(true);


		view.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				testNativeView = true;
			}
		});
		 */


		/*
		runOnUiThread(new Runnable() {
			@Override
			public void run() {

				///mWebSocketClient = new WebsocketSignal();
				//mWebSocketClient.Init(NativeRtcActivity.this);
				//Websocket._Init(WebrtcPeer.this);



				//start();
			}
		});
		 */
		new Thread(new Runnable() {
			@Override
			public void run() {
				rtcclient.ClientSignalPeerInit(1,"192.168.1.6", "zyh", "123", "1");
			}
		}).start();
	}
	private ReentrantLock imageArrayLock = new ReentrantLock();
	@Override
	public void onPreviewFrame(byte[] bytes, Camera camera) {
		//if (!testNativeView) return;
		if (isDestroy) return;
		if (bytes == null) return;	//System.out.println("onPreviewFrame byte null");
		imageArrayLock.lock();
		//view.drawPicture(data);
		rtcclient.SendNV21Image2(bytes, width, height, bytes.length);
		//Rtcclient.SendRGBAImage2(data, width, height, data.length);
		imageArrayLock.unlock();
		//System.out.println("onPreviewFrame......................................");
	}

	@Override
	public void surfaceCreated(SurfaceHolder surfaceHolder) {
		//Log.e(TAG,"surfaceCreated");
		try {
			//frameBuffer = new byte[((width * height) * ImageFormat.getBitsPerPixel(ImageFormat.NV21)) / 8];

			// Open the Camera in preview mode
			mCamera = Camera.open(camera_status);
			Camera.Parameters param = mCamera.getParameters();

			//https://www.jianshu.com/p/f07a42e1dd0a
			List<Camera.Size> listSize = param.getSupportedPreviewSizes();
			for (Camera.Size size : listSize) {
				System.out.println(size.width + "--------------------" + size.height);
			}


			param.setPictureFormat(PixelFormat.JPEG); //Sets the image format for picture 设定相片格式为JPEG，默认为NV21
			//param.setPreviewFormat(ImageFormat.NV21); //Sets the image format for preview picture，默认为NV21
			param.setPreviewFormat(ImageFormat.NV21); //Sets the image format for preview picture，默认为NV21
			//param.setPreviewFormat(ImageFormat.YV12);
			//param.setPictureFormat(PixelFormat.RGB_565);
			//param.setPictureFormat(PixelFormat.YCbCr_420_SP);
			//param.setPreviewSize(width, height);

			param.setPreviewSize(width, height);

			param.setFlashMode(Camera.Parameters.FOCUS_MODE_AUTO);
			if (!Build.MODEL.equals("KORIDY H30")) {
				param.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);// 1连续对焦
			} else {
				param.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
			}


			//<-处理变形
			int displayRotation = 0;
			WindowManager windowManager = (WindowManager)getSystemService(Context.WINDOW_SERVICE);
			int rotation = windowManager.getDefaultDisplay().getRotation();
			switch (rotation) {
				case Surface.ROTATION_0:
					displayRotation = 0;
					break;
				case Surface.ROTATION_90:
					displayRotation = 90;
					break;
				case Surface.ROTATION_180:
					displayRotation = 180;
					break;
				case Surface.ROTATION_270:
					displayRotation = 270;
					break;
			}
			Camera.CameraInfo info = new Camera.CameraInfo();
			Camera.getCameraInfo(0, info);
			int orientation;
			if (info.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
				orientation = (info.orientation - displayRotation + 360) % 360;
			} else {
				orientation = (info.orientation + displayRotation) % 360;
				orientation = (360 - orientation) % 360;
			}

			System.out.println("ImageFormat.getBitsPerPixel(ImageFormat.NV21)): " + ImageFormat.getBitsPerPixel(ImageFormat.NV21));

			//mCamera.addCallbackBuffer(new byte[((640 * 480) * ImageFormat.getBitsPerPixel(ImageFormat.NV21)) / 8]);
			//mCamera.addCallbackBuffer(new byte[((640 * 480) * ImageFormat.getBitsPerPixel(ImageFormat.RGB_565)) / 8]);
			//mCamera.addCallbackBuffer(frameBuffer); //Sets the image format for preview picture，默认为NV21
			//cameral.setPreviewCallbackWithBuffer()方法必须设置addCallbackBuffer(buffers)后onPreviewFrame()方法才会被持续调用

			//mCamera.setPreviewCallbackWithBuffer(this);

			mCamera.setPreviewCallback(this);

			mCamera.setParameters(param);
			mCamera.setDisplayOrientation(orientation);
			mCamera.setPreviewDisplay(surfaceHolder);
			mCamera.startPreview();

			//SendThread();

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		//Log.e(TAG,"surfaceDestroyed");
		if (mCamera != null) {
			mCamera.setPreviewCallback(null);   //切换摄像头时Camera is being used after Camera.release() was called
			mCamera.stopPreview();
			mCamera.release();
			mCamera = null;
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		isDestroy = true;
	}
}
